from sensor import MCP3004
import time
import Adafruit_DHT
import paho.mqtt.client as mqtt
import json

# MQTT服务器设置
MQTT_BROKER = "broker.emqx.io"  # 例如: "broker.hivemq.com"
MQTT_PORT = 1883  # MQTT默认端口
MQTT_TOPIC = "watering/Soil"  # 你要发布的MQTT主题
MQTT_CLIENT_ID = "mqttx_c7c21aa8"  # MQTT客户端ID

# 人工控制开关
watering_status = True

# MQTT回调函数
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("watering/Command")

# 回调函数，当收到消息时，触发该函数
def on_message(client, userdata, msg):
    global watering_status
    print(f"Received message: Topic - {msg.topic}, Payload - {msg.payload.decode()}")
    data = json.loads(msg.payload.decode())
    if data["command"] == "start":
        watering_status = True
        print("Auto Watering Started")
    elif data["command"] == "stop":
        watering_status = False
        print("Auto Watering Stopped")

# MQTT发布函数
def publish_data(client, Moisture):
    data = {
        "Moisture":Moisture
    }
    payload = json.dumps(data)
    client.publish(MQTT_TOPIC, payload)

# MQTT发布指令函数
def publish_command(client, command):
    data = {
        "command":command
    }
    payload = json.dumps(data)
    client.publish("watering/Water", payload)

# MQTT客户端
client = mqtt.Client(MQTT_CLIENT_ID)
client.on_connect = on_connect
client.on_message = on_message

# 连接到MQTT服务器
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 保持MQTT连接
client.loop_start()


try:
    mcp = MCP3004(bus=0, addr=0, vref=5.5)
    mcp._spi.max_speed_hz = 2106000

    while True:
        time.sleep(5)
        Moisture = mcp.read(0)

        if Moisture is not None:
            print(f"Moisture={Moisture}")
            publish_data(client, Moisture)
            # 将传感器值发送到MQTT服务器
            if watering_status:
                if Moisture <30:
                    # 将传感器值发送到MQTT服务器
                    publish_command(client, "start") # 如果需要浇水
                    time.sleep(3)
                    publish_command(client, "stop")
                elif Moisture >200:
                    publish_command(client, "stop")

        else:
            print('Failed to get reading. Try again!')

        time.sleep(4)  # 如果传感器数据输出间隔时间为4秒

finally:
    # 清理和断开MQTT连接
    client.loop_stop()
    client.disconnect()
